package cshi.common;

import scala.Int;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * Created by shichen on 2017/12/8.
 */
public class Java8Stream {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1,2,1,3,3,2,4);
        numbers.stream()
                .filter(i -> i % 2 == 0)
                .distinct()
                .forEach(System.out::println);
        numbers.stream()
                .skip(2)
                .limit(3)
                .forEach(System.out::println);

        List<String> words = Arrays.asList("java8", "lambdas", "in ", "action");
        List<Integer> wordLengths = words.stream()
                .map(String::length)
                .collect(Collectors.toList());

        //给定单词列表，返回包含各不相同的字符列表
        System.out.println("use flatMap to flatten: ");
        words.stream()
                .map(w -> w.split("")) //map返回的实际是Stream<String[]>，而我想要Stream<String>
                .distinct()
                .forEach(System.out::println);//这样做是达不到目的的，最终打印的是String[]这个类型的实例地址
        words.stream()
                .map(w -> w.split("")) //将每个单词转换为由字母组成的数组
                .map(Arrays::stream) //让每个数组变成一个单独的流
                .distinct()
                .forEach(System.out::println);//这个最终打印的是流类型的实例地址
        words.stream()
                .map(w -> w.split(""))
                .flatMap(Arrays::stream) //这样给distinct的就是Stream<String>
                .distinct()
                .forEach(System.out::println);

        //reduce处理更复杂的查询
        int sum = numbers.stream()
                .reduce(0, (a,b) -> a+b);
        System.out.println("sum=" + sum);

        Optional<Integer> sum2 = numbers.stream()
                .reduce(Integer::sum); //由于没有给定初始值，所以是Optional

        IntStream nums = IntStream.rangeClosed(1,100)
                .filter(i -> i%2 == 0);
        System.out.println(nums.count());
    }

}
